<?php

namespace Lib;

final class Token {
    use \Lib\Traits\Instance;

    /**
     * @var string
     */
    private $_token = null;

    /**
     * @var \Lib\Std
     */
    private $_std = null;

    /**
     * 获取token
     *
     * @return string
     */
    public function get() {
        return $this->_token;
    }

    /**
     * 获取token对应的数据
     *
     * @return \Lib\Std
     */
    public function getStd() {
        return ($this->_std ?: (new \Lib\Std([])));
    }

    /**
     * 生成 token
     *
     * @param array $data
     * @return boolean
     */
    public function built(array $data) {
        $redis = $this->getRedis();

        ksort($data);

        array_push($data, \Lib\Misc::randCode(32));
        array_push($data, mt_rand(1000, 9999));

        $token = sha1(implode('.', $data));
        $rKey  = sprintf(\Lib\Consts::TOKEN_KEY, $token);
        $redis->hMset($rKey, $data);
        $redis->expire($rKey, \Lib\Consts::EXPIRE_30DAY);

        $this->_token = $token;

        return true;
    }

    /**
     * 根据签名校验token
     *
     * @params string $token
     * @return boolean
     */
    public function valid($token) {
        $rKey = sprintf(\Lib\Consts::TOKEN_KEY, $token);
        $data = $this->getRedis()->hGetAll($rKey);
        $pass = false;

        if (!empty($data)) {
            $this->_std = new \Lib\Std($data);
            $pass       = true;
        }

        return $pass;
    }

    /**
     * 获取Redis
     *
     * @return \Redis
     */
    protected function getRedis() {
        return \Yaf\Registry::get('redis');
    }

    /**
     * @param       $token
     * @param array $params
     * @return bool
     */
    public function delete($token) {
        $rKey = sprintf(\Lib\Consts::TOKEN_KEY, $token);
        $this->getRedis()->del($rKey);

        return true;
    }
}

